package com.jzr.medical.controller.api;

import com.jzr.common.entity.vo.Result;
import com.jzr.medical.db1.model.TDevice;
import com.jzr.medical.db1.model.TPatientExtra;
import com.jzr.medical.db1.service.CareLabelService;
import com.jzr.medical.db1.service.NurseService;
import com.jzr.medical.db1.service.PatientService;
import com.jzr.medical.db1.vo.BedPatientVo;
import com.jzr.netty.common.base.ConnectionException;
import com.jzr.netty.common.base.SendException;
import com.jzr.netty.common.protocol.ReloadDataDeptRequest;
import com.jzr.netty.common.protocol.ReloadDataResponse;
import com.jzr.netty.common.service.AdminNettyClient;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.web.bind.annotation.*;

import java.util.Arrays;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

@RestController
@RequestMapping("/api/patient")
public class PatientController {
    @Value("${nettyServer.ip}")
    private String nettyServerIp;

    @Value("${nettyServer.port}")
    private int nettyServerPort;

    @Autowired
    private PatientService patientService;

    @Autowired
    private NurseService nurseService;

    @Autowired
    private CareLabelService careLabelService;

    @RequestMapping("/selectBedPatientVo")
    public Result<List<BedPatientVo>> selectBedPatientVo(String deptCode){
        List<BedPatientVo> list = patientService.selectBedPatientVo(deptCode);
        return Result.success("成功",list);
    }

    @GetMapping("/getFormData")
    public Result<Map<String,Object>> getFormatData(Integer patientId,String deptCode){
        HashMap<String,Object> map = new HashMap<String,Object>();
        map.put("nurseList",nurseService.codeList("",deptCode));
        map.put("careLabelList",careLabelService.codeList(patientId));
        return Result.success("成功",map);
    }

    @PostMapping("/saveFormData")
    public Result<Integer> saveFormData(BedPatientVo bedPatientVo,@RequestParam("careLabelIds[]") Integer[] careLabelIds){
        try {
            patientService.saveCareLabelList(bedPatientVo.getId(), Arrays.asList(careLabelIds));
            TPatientExtra patientExtra = new TPatientExtra();
            patientExtra.setPatientId(bedPatientVo.getId());
            patientExtra.setNurseCode(bedPatientVo.getNurseCode());
            patientExtra.setDiagnose(bedPatientVo.getDiagnose());
            patientExtra.setAllergy(bedPatientVo.getAllergy());
            patientService.saveExtra(patientExtra);
        }catch (Exception e){
            return Result.fail("保存失败,"+e.getMessage());
        }

        ReloadDataResponse resp = null;
        try {
            if (bedPatientVo.getId() != null) {
                TDevice device = patientService.getBedDeviceByPatientId(bedPatientVo.getId());
                if(device != null) {
                    resp = reloadData(device.getDeptCode(), device.getDeviceType(), device.getDeviceIp());
                }
            }
        }catch (Exception e) {
            e.printStackTrace();
            return Result.fail("保存成功，但是刷新床头卡失败，"+e.getMessage());
        }
        if(resp == null || resp.getDeviceCount() == null || resp.getDeviceCount() ==0) {
            return Result.success("保存成功,但是没有刷新对应的床头卡（设备不在线）", 0);
        }else{
            return Result.success("保存成功,", resp.getDeviceCount());
        }

    }

    private ReloadDataResponse reloadData(String deptCode, Integer deviceType, String deviceIp) throws ConnectionException, SendException {
        ReloadDataDeptRequest request = new ReloadDataDeptRequest();
        request.setDeptCode(deptCode);
        request.setDeviceIp(deviceIp);
        request.setDeviceType(deviceType);
        try(AdminNettyClient client = new AdminNettyClient(nettyServerIp, nettyServerPort)) {
            ReloadDataResponse response = (ReloadDataResponse) client.send(request);
            return response;
        }
    }
}
